package cn.com.connected.service.impl;

import cn.com.connected.base.cache.CacheService;
import cn.com.connected.base.exception.BusinessException;
import cn.com.connected.base.exception.ErrorCode;
import cn.com.connected.base.utils.baidu.HttpUtil;
import cn.com.connected.common.emnus.CacheKey;
import cn.com.connected.service.BaiduService;
import cn.com.connected.vo.Conclusion;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.klock.annotation.Klock;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.stream.Collectors;

/**
 * @author 邵明生
 * @version 3.0
 * @Description
 * @date 2021-10-22 10:28
 **/

@Slf4j
@Service
public class BaiduServiceImpl implements BaiduService {

    @Value("${baidu.censor.APP_ID}")
    private String APP_ID;

    @Value("${baidu.censor.API_KEY}")
    private String API_KEY;

    @Value("${baidu.censor.SECRET_KEY}")
    private String SECRET_KEY;

    @Value("${baidu.censor.TEXT_CENSOR}")
    private String TEXT_CENSOR;

    @Value("${baidu.censor.TOKEN_URL}")
    private String TOKEN_URL;

    @Resource
    private CacheService cacheService;

    @Override
    public Conclusion textCensor(String content){
        try{

            if (StringUtils.isEmpty(content) || StringUtils.isEmpty(content.trim())){
                return null;
            }

            String param = "text=" + content;

            String accessToken = getAccessToken();

            String result = HttpUtil.post(TEXT_CENSOR, accessToken, param);
            JSONObject jr = JSONObject.parseObject(result);
            JSONArray array = jr.getJSONArray("data");
            String msg = CollectionUtils.isEmpty(array)?"":array.stream().map(a->{
                JSONObject aa = (JSONObject) a;
                return aa.getString("msg");
            }).collect(Collectors.joining());
            return Conclusion.builder()
                    .conclusion(jr.getString("conclusion"))
                    .conclusionType(jr.getInteger("conclusionType"))
                    .msg(msg)
                    .build();
        }catch (Exception e){
            log.error(e.getMessage());
            throw new BusinessException(ErrorCode.SERVICE_ERROR);
        }

    }

    //获取accessToken 有效期30天
    @Klock
    public String getAccessToken() throws Exception {

        String token = cacheService.getObject(CacheKey.baidu_access_token);
        if (token!=null){
            return  token;
        }

        String getAccessTokenParams = "grant_type=client_credentials" + "&client_id=" + API_KEY + "&client_secret=" + SECRET_KEY;
        String result = HttpUtil.postGeneralUrl(TOKEN_URL,"application/x-www-form-urlencoded",getAccessTokenParams,"utf-8");

        token = JSONObject.parseObject(result).getString("access_token");
        int expires = JSONObject.parseObject(result).getInteger("expires_in");

        cacheService.putObject(CacheKey.baidu_access_token,token,expires-100);
        return token;
    }

}
